package sword.T52;

import util.ListNode;

/**
 * @Author: 18362
 * @Create: 2022-04-09 23:36:31 星期六
 */
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode p = headA, q = headB;
        boolean flagP = false, flagQ = false;
        while (p != q && p != null && q != null) {
            if (p.next == null && !flagP) {
                p = headB;
                flagP = true;
            } else
                p = p.next;
            if (q.next == null && !flagQ) {
                q = headA;
                flagQ = true;
            } else
                q = q.next;
        }
        return p == q ? p : null;
    }
}